package com.wy.controller.wy;

import com.wy.bean.HouseholdBean;
import com.wy.bean.TreeBean;
import com.wy.model.sys.*;
import com.wy.service.sys.UserService;
import com.wy.service.wy.BuildingService;
import com.wy.service.wy.HouseService;
import com.wy.service.wy.HouseholdService;
import com.wy.service.wy.ResidenceService;
import com.wy.utils.BaseResponseInfo;
import com.wy.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Auther: tracy
 * @Date: 2018/8/20 16:58
 * @Description: 小区管理
 */
@RestController
@RequestMapping("/residences")
@Api(value="API - ResidenceController",tags={"小区管理"})
public class ResidenceController {

    private Logger log = LoggerFactory.getLogger(ResidenceController.class);

    @Resource(name = "residenceServiceImpl")
    private ResidenceService residenceService;

    @Resource(name = "buildingServiceImpl")
    private BuildingService buildingService;

    @Resource(name = "houseServiceImpl")
    private HouseService houseService;

    @Resource(name = "householdServiceImpl")
    private HouseholdService householdService;


    @Resource(name = "userServiceImpl")
    private UserService userService;

    @GetMapping("")
    @ApiOperation(value="residencesList",notes="获取小区列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false,dataType = "Int", defaultValue = "10"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = false,dataType = "Int",defaultValue = "1"),
            @ApiImplicitParam(name = "projectName", value = "小区名称", required = false,dataType = "String",defaultValue = "")
//            @ApiImplicitParam(name = "rid", value = "小区ID", required = false,dataType = "String",example = "1,2,3",defaultValue = ""),
    })
    public PageResult residencesList(Integer pageSize, Integer page,String projectName,HttpServletRequest request) {
        List<String> rids = new ArrayList<>();
        UserEntity userEntity = userService.getUserByLoginName(request.getUserPrincipal().getName());
        if(null != userEntity) {
            String rid = userEntity.getRid();
            if(!StringUtils.isEmpty(rid)){
                List list = Arrays.asList(rid.split(","));
                rids = new ArrayList(list);
            }
        }
        PageResult pageResult = new PageResult();
        if("admin".equals(userEntity.getLoginName())){
            rids = null;
        }else {
            rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
        }
        pageResult.setData(residenceService.residenceList(pageSize, page * pageSize, projectName, rids));
        pageResult.setTotalCount(residenceService.residenceSize(pageSize, page * pageSize, projectName, rids));
        return pageResult;
    }

    /**
     * 新建小区名称
     * @param residenceEntity
     * @return
     */
    @PostMapping("/residence")
    @ApiOperation(value="insertResidence",notes="新建小区")
    public BaseResponseInfo insertResidence(@RequestBody Residence residenceEntity) {
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isEmpty(residenceEntity.getProjectName())) {
            map.put("message","小区名称不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        if(StringUtils.isEmpty(residenceEntity.getVillageCode())) {
            map.put("message","小区编码不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        //根据名称获取小区，判读小区的唯一性
        List<Residence> list = residenceService.getResidenceByName(residenceEntity.getProjectName());
        if(list.size() >0) {
            map.put("message","小区："+residenceEntity.getProjectName()+",已存在！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        residenceService.insertResidence(residenceEntity);
        log.debug("The method is ending");
        return baseResponseInfo;
    }

    /**
     * 修改小区信息
     *
     * @param residenceEntity
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    public BaseResponseInfo updateResidence(@RequestBody Residence residenceEntity, @PathVariable int id) {
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isEmpty(residenceEntity.getProjectName())) {
            map.put("message","小区名称不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        if(StringUtils.isEmpty(residenceEntity.getVillageCode())) {
            map.put("message","小区编码不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        //根据名称获取小区，判读小区的唯一性
        List<Residence> list = residenceService.getResidenceByName(residenceEntity.getProjectName());
        if(list.size() >0) {
            if(list.get(0).getId() != residenceEntity.getId()) {
                map.put("message", "小区：" + residenceEntity.getProjectName() + ",已存在！");
                baseResponseInfo.code = 500;
                baseResponseInfo.data = map;
                return baseResponseInfo;
            }
        }
        residenceService.updateResidence(residenceEntity);
        log.debug("The method is ending");
        return baseResponseInfo;
    }

    /**
     * 删除小区信息
     *
     * @param groupId
     * @return
     */
    @DeleteMapping("")
    public void deleteMenus(@RequestBody List<String> groupId) {
        residenceService.deleteResidences(groupId);
    }

    /**
     * 获取所有的小区
     * @return
     */
    @GetMapping("/all")
    public BaseResponseInfo getAllResidence(){
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        baseResponseInfo.data = residenceService.getAllResidence();
        return baseResponseInfo;
    }

    @GetMapping("/getResidence")
    public BaseResponseInfo getResidence(HttpServletRequest request) {
        List<String> rids = new ArrayList<>();
        UserEntity userEntity = userService.getUserByLoginName(request.getUserPrincipal().getName());
        if(null != userEntity) {
            String rid = userEntity.getRid();
            if(!StringUtils.isEmpty(rid)){
                List list = Arrays.asList(rid.split(","));
                rids = new ArrayList(list);
            }
        }
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        if("admin".equals(userEntity.getLoginName())){
            baseResponseInfo.data = residenceService.getAllResidence();
        }else {
            rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
            baseResponseInfo.data = residenceService.getResidence(rids);
        }
        return baseResponseInfo;
    }

    /**
     * 将住户信息组装成树结构
     * @param households
     * @return
     */
    private TreeBean convertToTreeBean(HouseholdBean households){
        TreeBean treeBean = new TreeBean();
        treeBean.setId(households.getId());
        treeBean.setTitle(households.getHouseholdName());
        treeBean.setExpand(false);
        treeBean.setChecked(false);
        treeBean.setChildren(null);
        treeBean.setType(3);
        return treeBean;
    }

    /**
     * 将房屋信息组装成树结构
     * @param houses
     * @return
     */
    private TreeBean convertToTreeBean(Houses houses,Map<Integer,List<TreeBean>> householdsMap){
        TreeBean treeBean = new TreeBean();
        treeBean.setId(houses.getId());
        treeBean.setTitle(houses.getHouseCode());
        treeBean.setExpand(false);
        treeBean.setChecked(false);
        treeBean.setChildren(householdsMap.get(houses.getId()));
        treeBean.setType(2);
        return treeBean;
    }

    /**
     * 将楼栋信息组装成树结构
     * @param building
     * @param building
     * @return
     */
    private TreeBean convertToTreeBean(Buildings building,Map<Integer,List<TreeBean>> houseMap){
        TreeBean treeBean = new TreeBean();
        treeBean.setId(building.getId());
        treeBean.setTitle(building.getBuildingName());
        treeBean.setExpand(false);
        treeBean.setChecked(false);
        treeBean.setChildren(houseMap.get(building.getId()));
        treeBean.setType(1);
        return treeBean;
    }

    /**
     * 将小区信息组装成树结构
     * @param residence
     * @param buildingMap
     * @return
     */
    private TreeBean convertToTreeBean(Residence residence,Map<Integer,List<TreeBean>> buildingMap){
        TreeBean treeBean = new TreeBean();
        treeBean.setId(residence.getId());
        treeBean.setTitle(residence.getProjectName());
        treeBean.setExpand(false);
        treeBean.setChecked(false);
        treeBean.setChildren(buildingMap.get(residence.getId()));
        treeBean.setType(0);
        return treeBean;
    }

    /**
     * 根据用户名查询可以匹配的小区树结构
     * @return
     */
    @GetMapping("/residenceTree")
    public BaseResponseInfo getResidenceTree(HttpServletRequest request){
        List<String> rids = new ArrayList<>();
        UserEntity userEntity = userService.getUserByLoginName(request.getUserPrincipal().getName());
        if(null != userEntity) {
            String rid = userEntity.getRid();
            if(!StringUtils.isEmpty(rid)){
                List list = Arrays.asList(rid.split(","));
                rids = new ArrayList(list);
            }
        }

        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        List<TreeBean> treeBeanList = new ArrayList<>();
        List<HouseholdBean> householdsList = new ArrayList<>();
        //获取所有的住户封装成map<houseId,households>
        if("admin".equals(userEntity.getLoginName())) {
            householdsList = householdService.getHouseholdList(rids);
        }else {
            rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
            householdsList = householdService.getHouseholdList(rids);
        }
        Map<Integer,List<TreeBean>> householdsMap = new HashMap<>();
        Map<Integer,List<TreeBean>> housesMap = new HashMap<>();
        Map<Integer,List<TreeBean>> buildingMap = new HashMap<>();
        List<TreeBean> temp = null;
        for(HouseholdBean households : householdsList) {
            temp = householdsMap.get(households.getHouseId());  //获取当前房屋下的住户
            if(null == temp) {
                temp = new ArrayList<>();
            }
            temp.add(convertToTreeBean(households));
            householdsMap.put(households.getHouseId(),temp); //更新集合
            temp = null;
        }

        //获取所有房屋信息封装成map<buildingId,houses>
        List<Houses> housesList = houseService.getHouseList();
        for(Houses house : housesList) {
            temp = housesMap.get(house.getBuildingId());
            if(null == temp) {
                temp = new ArrayList<>();
            }
            temp.add(convertToTreeBean(house,householdsMap));
            housesMap.put(house.getBuildingId(),temp); //更新集合
            temp = null;
        }

        //获取所有楼栋信息封装成map<buildingId,houses>
        List<Buildings> buildingList = buildingService.getBuildingList();
        for(Buildings building : buildingList) {
            temp = buildingMap.get(building.getProjectId());
            if(null == temp) {
                temp = new ArrayList<>();
            }
            temp.add(convertToTreeBean(building,housesMap));
            buildingMap.put(building.getProjectId(),temp); //更新集合
            temp = null;
        }

        //获取所有小区信息封装成map<buildingId,houses>
        List<Residence> residenceList = residenceService.getResidence(rids);
        for(Residence residence : residenceList) {
            treeBeanList.add(convertToTreeBean(residence,buildingMap));
        }
        baseResponseInfo.data = treeBeanList;
        return baseResponseInfo;
    }

    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response,String projectName,String username) throws Exception {
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename="+new String( "小区信息.xls".getBytes("gb2312"), "ISO8859-1" ));
        List<String> rids = new ArrayList<>();
        UserEntity userEntity = userService.getUserByLoginName(username);
        if(null != userEntity) {
            String rid = userEntity.getRid();
            if(!org.springframework.util.StringUtils.isEmpty(rid)){

                List list = Arrays.asList(rid.split(","));
                rids = new ArrayList(list);
            }
        }
        List<Residence> list = new ArrayList<>();
        if("admin".equals(username)) {
            rids = null;
        }else {
            rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
        }
        list = residenceService.residenceList(null, null, projectName, rids);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Residence.class, list);
        workbook.write(response.getOutputStream());
    }

    /**
     * 数据导入
     * @param file
     */
    @PostMapping("/import")
    public Map<String,String> importExcel(MultipartFile file){
        Map<String,String> map = FileUtil.judgeRepeatExcel(file,2,1);
        if(map.isEmpty()) {
            List<Residence> residenceList = FileUtil.importExcel(file, 0, 1, Residence.class);

            if (residenceList != null) {
                System.out.println("导入数据一共【" + residenceList.size() + "】行");
               List<Residence> temp = residenceService.selectByName(residenceList);
               if(temp.size() == 0){
                   residenceService.insertBatch(residenceList);
               }else{
                   for(Residence residence : temp){
                       map.put(String.valueOf(residence.getId()),residence.getProjectName());
                   }

               }

            }
        }
        return  map;
    }

}
